<template>
  <div class="chat-container">
    <div class="sidebar" :style="{ width: sidebarVisible ? sidebarWidth + 'px' : '0px' }" :class="{ 'sidebar-hidden': !sidebarVisible }">
      <SessionList
        :sessions="sessions"
        :current-session="currentSession"
        @select="handleSelectSession"
        @delete="handleDeleteSession"
        @create="handleCreateSession"
      />
      
      <div class="user-info">
        <div class="user-display">
          <span class="user-name">{{ store.currentUser?.username || '未知用户' }}</span>
        </div>

        <div class="user-actions">
          <button class="secondary" @click="handleClearHistory">
            清空当前会话
          </button>
          <button class="danger" @click="handleLogout">
            退出登录
          </button>
        </div>
      </div>
    </div>
    
    <!-- 可调整的分界线 -->
    <div
      v-if="sidebarVisible"
      class="resizer"
      @mousedown="startResize"
      :class="{ resizing: isResizing }"
    ></div>

    <div class="chat-area">
      <div class="chat-header">
        <div class="header-left">
          <button
            class="sidebar-toggle"
            @click="toggleSidebar"
            :title="sidebarVisible ? '隐藏边栏' : '显示边栏'"
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
              <line x1="3" y1="6" x2="21" y2="6"></line>
              <line x1="3" y1="12" x2="21" y2="12"></line>
              <line x1="3" y1="18" x2="21" y2="18"></line>
            </svg>
          </button>
          <div class="header-titles">
            <h1>DeepSeek-KAI.v.0.0.1 聊天</h1>
            <h2>当前会话: {{ currentSessionName }}</h2>
          </div>
        </div>
      </div>
      
      <div v-if="error" class="error-message">{{ error }}</div>
      
      <div class="messages-container">
        <div v-if="messages.length === 0" class="empty-state">
          开始与 DeepSeek-KAI.v.0.0.1 的对话吧！
        </div>
        
        <ChatMessage
          v-for="(msg, index) in messages"
          :key="msg.id"
          :message-id="msg.id"
          :is-user="msg.isUser"
          :content="msg.content"
          :timestamp="msg.timestamp"
          :versions="msg.versions"
          :current-version-index="msg.currentVersionIndex"
          :is-last-ai-message="!msg.isUser && index === messages.length - 1"
          @regenerate="handleRegenerate"
          @switch-version="handleSwitchVersion"
        />
        
        <div v-if="loading" class="loading-indicator">
          <div class="loading"></div>
        </div>
      </div>
      
      <ChatInput
        :loading="loading"
        @send="handleSendMessage"
        @abort="handleAbortGeneration"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, computed, ref, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from '../store';
import api from '../api';
import SessionList from '../components/SessionList.vue';
import ChatMessage from '../components/ChatMessage.vue';
import ChatInput from '../components/ChatInput.vue';

const store = useStore();
const router = useRouter();

// 侧边栏宽度调整
const sidebarWidth = ref(300);
const isResizing = ref(false);
const sidebarVisible = ref(true);

// 计算属性
const sessions = computed(() => {
  // 将sessions数组转换为包含名称的对象数组
  return store.sessions.map(sessionId => ({
    session_id: sessionId,
    session_name: store.sessionNames[sessionId] || sessionId
  }));
});
const currentSession = computed(() => store.currentSession);
const currentSessionName = computed(() => store.sessionNames[currentSession.value] || currentSession.value);
const messages = computed(() => store.messages[currentSession.value] || []);
// 🔄 只有当前会话在loading时才显示loading指示器
const loading = computed(() => store.loading && store.loadingSession === currentSession.value);
const error = computed(() => store.error);

// 初始化加载历史记录
const loadHistory = async (sessionId) => {
  try {
    store.setLoading(true, sessionId);
    const response = await api.getHistory(sessionId);
    store.loadHistory(sessionId, response.data.history);
  } catch (err) {
    store.setError(err.response?.data?.error || '加载历史记录失败');
  } finally {
    store.setLoading(false);
  }
};

// 挂载时加载会话列表和当前会话历史
onMounted(async () => {
  // 先加载会话列表
  await store.loadSessions(api);
  
  // 延迟加载历史记录，避免阻塞页面渲染
  setTimeout(() => {
    loadHistory(currentSession.value);
  }, 500);
});

// 处理选择会话
const handleSelectSession = async (sessionId) => {
  // 如果正在生成回复，先中止请求
  if (loading.value) {
    console.log('⚠️ 切换会话，中止当前生成');
    api.abort();
    store.setLoading(false);
  }

  store.setCurrentSession(sessionId);
  await loadHistory(sessionId);
};

// 处理删除会话
const handleDeleteSession = async (sessionId) => {
  try {
    // 调用删除会话API（完全删除会话记录）
    await api.deleteSession(sessionId);
    
    // 从前端状态中移除
    store.removeSession(sessionId);
    store.clearSessionMessages(sessionId);
    
    // 从会话名称映射中移除
    if (store.sessionNames[sessionId]) {
      delete store.sessionNames[sessionId];
      localStorage.setItem('sessionNames', JSON.stringify(store.sessionNames));
    }
    
    console.log(`✅ 会话 ${sessionId} 已成功删除`);
  } catch (err) {
    store.setError(err.response?.data?.error || '删除会话失败');
    console.error('删除会话失败:', err);
  }
};

// 处理创建会话
const handleCreateSession = (sessionId) => {
  store.addSession(sessionId);
  store.clearSessionMessages(sessionId);
};

// 处理发送消息
const handleSendMessage = async (payload) => {
  const isObject = payload && typeof payload === 'object';
  const content = isObject ? (payload.content || '') : (payload || '');
  const file = isObject ? (payload.file || null) : null;
  const mode = isObject ? (payload.mode || 'shallow') : 'shallow';

  // 🔒 记录发送请求时的会话ID，确保回复添加到正确的会话
  const requestSessionId = currentSession.value;

  // 检查是否是新会话（没有消息）
  const isNewSession = !messages.value || messages.value.length === 0;

  // 添加用户消息到界面（展示文本，如有文件则在前端提示）
  const displayContent = file ? `${content}\n\n[已附加文件：${file.name}]` : content;
  store.addMessage(requestSessionId, true, displayContent);

  if (!content.trim() && !file) {
    store.setError('请输入消息内容或上传文件');
    return;
  }
  
  try {
    // 🔄 设置loading状态，并记录是哪个会话在loading
    store.setLoading(true, requestSessionId);

    // 深度模式提示
    if (mode === 'deep') {
      console.log('🧠 深度思考模式启动，可能需要较长时间...');
    }

    // 调用API发送消息
    let response;
    if (file) {
      // 如果有文件，使用带文件的聊天接口
      response = await api.chatWithFile(requestSessionId, content, file, mode);
    } else {
      // 如果没有文件，使用普通聊天接口
      response = await api.chat(requestSessionId, content, mode);
    }

    // 🔒 使用记录的会话ID，而不是当前会话ID（防止切换会话后回复添加到错误位置）
    store.addMessage(requestSessionId, false, response.data.reply);
    
    // 如果是新会话，重新加载会话列表以获取AI生成的会话名称
    if (isNewSession) {
      await store.loadSessions(api);
    }
  } catch (err) {
    if (err.code === 'ECONNABORTED') {
      store.setError('请求超时，深度思考模式可能需要更长时间，请重试');
    } else {
      store.setError(err.response?.data?.error || '发送消息失败');
    }
  } finally {
    // 🔄 清除loading状态
    store.setLoading(false);
  }
};

// 处理清空历史
const handleClearHistory = async () => {
  if (confirm(`确定要清空当前会话 "${currentSessionName.value}" 的历史记录吗？`)) {
    try {
      await api.clearHistory(currentSession.value);
      store.clearSessionMessages(currentSession.value);
    } catch (err) {
      store.setError(err.response?.data?.error || '清空历史记录失败');
    }
  }
};

// 处理中止生成
const handleAbortGeneration = () => {
  api.abort();
  store.setLoading(false);
  store.setError('生成已中止');
};

// 处理退出登录
const handleLogout = () => {
  if (confirm('确定要退出登录吗？')) {
    store.clearApiKey();
    router.push('/login');
  }
};

// 切换边栏显示/隐藏
const toggleSidebar = () => {
  sidebarVisible.value = !sidebarVisible.value;
};

// 处理重新生成
const handleRegenerate = async (messageId) => {
  // 找到最后一条AI消息，暂时隐藏其内容
  const messages = store.messages[currentSession.value];
  const lastAiMessage = messages.filter(msg => !msg.isUser).pop();

  if (!lastAiMessage) return;

  try {
    store.setLoading(true);

    // 调用重新生成API
    const response = await api.regenerate(currentSession.value, 'shallow');

    // 添加新版本到store
    store.regenerateLastMessage(currentSession.value, response.data.reply);
  } catch (err) {
    store.setError(err.response?.data?.error || '重新生成失败');
  } finally {
    store.setLoading(false);
  }
};

// 处理版本切换
const handleSwitchVersion = (messageId, versionIndex) => {
  store.switchVersion(currentSession.value, messageId, versionIndex);
};

// 开始调整宽度
const startResize = (e) => {
  isResizing.value = true;
  document.addEventListener('mousemove', handleResize);
  document.addEventListener('mouseup', stopResize);
  document.body.style.cursor = 'col-resize';
  document.body.style.userSelect = 'none';
  e.preventDefault();
};

// 处理调整宽度
const handleResize = (e) => {
  if (!isResizing.value || !sidebarVisible.value) return;

  const newWidth = e.clientX;
  const minWidth = 290;
  const maxWidth = window.innerWidth * 0.7;

  if (newWidth >= minWidth && newWidth <= maxWidth) {
    sidebarWidth.value = newWidth;
  }
};

// 停止调整宽度
const stopResize = () => {
  isResizing.value = false;
  document.removeEventListener('mousemove', handleResize);
  document.removeEventListener('mouseup', stopResize);
  document.body.style.cursor = '';
  document.body.style.userSelect = '';
};

// 组件卸载时清理事件监听器
onUnmounted(() => {
  document.removeEventListener('mousemove', handleResize);
  document.removeEventListener('mouseup', stopResize);
});
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
}

.sidebar {
  display: flex;
  flex-direction: column;
  background-color: var(--card-bg);
  border-right: 1px solid var(--border-color);
  min-width: 200px;
  max-width: 70vw;
  transition: width 0.3s ease;
  overflow: hidden;
}

.sidebar.sidebar-hidden {
  width: 0 !important;
  min-width: 0;
  border-right: none;
}

.user-info {
  padding: 1rem;
  border-top: 1px solid var(--border-color);
}

.user-display {
  margin-bottom: 1rem;
}

.user-name {
  font-weight: 500;
  color: var(--primary-color);
}

.user-actions {
  display: flex;
  gap: 0.5rem;
}

.user-actions button {
  flex: 1;
  min-width: 0;
}

/* 可调整的分界线 */
.resizer {
  width: 4px;
  background-color: var(--border-color);
  cursor: col-resize;
  position: relative;
  transition: background-color 0.2s ease;
  flex-shrink: 0;
}

.resizer:hover {
  background-color: var(--primary-color);
}

.resizer.resizing {
  background-color: var(--primary-color);
}

.resizer::before {
  content: '';
  position: absolute;
  top: 0;
  left: -2px;
  right: -2px;
  bottom: 0;
  background-color: transparent;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color);
}

.chat-header {
  padding: 1rem;
  background-color: var(--card-bg);
  border-bottom: 1px solid var(--border-color);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.sidebar-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 44px;
  height: 44px;
  background: var(--card-bg);
  border: 2px solid var(--border-color);
  border-radius: 8px;
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.2s ease;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sidebar-toggle:hover {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.sidebar-toggle:active {
  transform: translateY(0) scale(0.95);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-titles {
  flex: 1;
  min-width: 0;
}

.chat-header h1 {
  color: var(--primary-color);
  margin-bottom: 0.25rem;
}

.chat-header h2 {
  font-size: 1rem;
  color: var(--text-secondary);
  font-weight: 500;
}

.messages-container {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.empty-state {
  margin: auto;
  color: var(--text-secondary);
  font-size: 1.25rem;
  text-align: center;
  padding: 2rem;
}

.loading-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 1rem auto;
  color: var(--text-secondary);
}

</style>
